package cn.wolfcode.rbac.util;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class CRMExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public String handleException(Exception ex, Model model) throws ServletException, IOException {
        model.addAttribute("ex", ex);
        ex.printStackTrace();
        return "common/error";
    }

    @ExceptionHandler(UnauthorizedException.class)
    public void handleException(Exception ex, Model model, HttpServletResponse response, HandlerMethod method) throws Exception {
        ResponseBody annotation = method.getMethodAnnotation(ResponseBody.class);
        ex.printStackTrace();
        if (annotation != null) {
            response.setContentType("text/json;charset=utf-8");
            JsonResult jsonResult = new JsonResult("无权限操作", false);
            response.getWriter().print(JSON.toJSONString(jsonResult));
        } else {
            throw ex;
        }
    }
}
